package core.utils;

import java.io.File;
import java.nio.file.Files;

/**
 * @author wsz
 * @date 2021/11/16 17:18
 **/
public class WebClassLoader extends ClassLoader{

    private String classPath;

    public WebClassLoader (String classPath) {
        this.classPath = classPath;
    }

    @Override
    public Class<?> findClass(String name) {
        try {
            // 获取当前项目路径下的class文件并生成Class文件
            File file = new File("");
            String realPath = file.getCanonicalPath() + "/" + classPath + name.replace(".", "/") + ".class";

            File targetClass = new File(realPath);
            byte[] allBytes = Files.readAllBytes(targetClass.toPath());
            return defineClass(name, allBytes, 0, allBytes.length);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("cannot found class by realPath=" );
        }
    }
}
